<template>
  <div>
    <el-form
      v-if="formObj && formObj.length > 0"
      ref="ruleForm"
      :model="formData"
      class="demo-ruleForm"
      :label-position="labelPosition"
      :validate-on-rule-change="false"
      :label-width="labelwidth ? labelwidth : '120px'"
      size="small"
      :inline="inline"
      autocomplete="off"
    >
      <e-desc
        margin="0 12px"
        :class="{ border: !borders }"
        :label-width="labelwidth ? labelwidth : '120px'"
      >
        <!-- 进行遍历json -->
        <el-col
          v-for="(formobj, index) in formObj"
          v-show="colsiShow(formobj,formData)"
          :key="index"
          :span="computedSpan(formobj.width)"
          :class="{
            'desc-item': borders,
            'desc-border': istext(formobj.label),
          }"
        >
          <!-- 'desc-borders' : istext(formobj.label) -->
          <div v-if="formobj.title" class="title clearfix">
            <span></span> {{ formobj.text }}
          </div>
          <div v-else-if="istext(formobj.label)" class="text">
            {{ formobj.label }}: {{ formData[formobj.prop] }}
            <span style="margin-left: 10px">{{
              formData[formobj.propname]
            }}</span>
          </div>
          <div v-else-if="istext1(formobj.label)" class="text1">
            {{ formobj.label }}: {{ formData[formobj.prop] }}
            <span style="margin-left: 10px">{{
              formData[formobj.propname]
            }}</span>
          </div>
          <div v-else class="desc-item-content">
            <!-- v-if=" formobj.label" -->
            <label
              v-if="borders"
              :class="{ 'desc-item-label': borders }"
              :style="{
                width: formobj.labelWidth ? formobj.labelWidth : labelwidth || '120px',
              }"
            ><span
               v-show="type !== 'select' && formobj.rules && formobj.rules.length>0 && formobj.rules[0].required === true"
               class="redstar"
             >*</span>
              {{ formobj.label }}</label>
            <!-- 填充eformitem -->
            <el-form-item
              :prop="formobj.prop"
              :rules="type === 'select' ? null : formobj.rules"
              :label-width="formobj.labelWidth || labelwidth"
              :label="borders === true ? '' : formobj.label"
              :class=" type === 'select' ? 'selectform' : ''"
            >
              <!-- :style="`width: calc(100% - ${formobj.labelWidth ? formobj.labelWidth : '120px'})`" -->
              <div class="desc-item-value desc-item-box">
                <!-- 如果是表单查看 -->
                <template v-if="type === 'select'">
                  <!-- 文件 -->
                  <el-upload
                    v-if="formobj.upload || formobj.type === 'upload'"
                    :ref="formobj.prop"
                    :disabled="true"
                    :before-upload="beforeUpload"
                    :accept="formobj.accept ? formobj.accept : ''"
                    :file-list="
                      formobj.uploadObj.fileList
                        ? formobj.uploadObj.fileList
                        : []
                    "
                    action=""
                    :limit="formobj.uploadObj.limit"
                    :on-preview="handlePictureCardPreview"
                    :class="{
                      hide: true,
                    }"
                    :list-type="
                      formobj.listType ? formobj.listType : 'picture-card'
                    "
                  />
                  <span
                    v-else
                    v-text="
                      (formData[formobj.propname] &&
                        formData[formobj.propname].toString()) ||
                        (formData[formobj.prop] &&
                          formData[formobj.prop].toString())
                    "
                  ></span>
                  <!-- 计量单位 -->
                  <span v-if="formobj.unit" class="left10">{{
                    formobj.unit
                  }}</span>
                  <!-- 提示信息 -->
                  <el-tooltip v-show="formobj.tip" placement="top">
                    <div slot="content" v-html="formobj.tip"></div>
                    <i class="el-icon-question" style="display:inline;color:#a1a0a0"></i>
                  </el-tooltip>
                </template>
                <template v-else>
                  <!-- inupt输入框 -->
                  <el-input
                    v-if="formobj.input || formobj.type === 'input'"
                    v-model="formData[formobj.prop]"
                    class="input"
                    size="small"
                    autocomplete="off"
                    :type="formobj.type || 'text'"
                    :style="formobj.style"
                    :readonly="formobj.readonly"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                    @input="inputINPUT($event, index, formobj.prop)"
                    @change="inputChange($event, index, formobj.prop)"
                  />
                  <!-- textarea输入框 -->
                  <!-- formobj.style &&  -->
                  <el-input
                    v-if="formobj.textarea || formobj.type === 'textarea'"
                    v-model="formData[formobj.prop]"
                    size="small"
                    type="textarea"
                    :style="formobj.style || { width: 'width: 100%' }"
                    :rows="formObj.rows"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                  />
                  <!-- select选择器 -->
                  <el-select
                    v-if="formobj.select || formobj.type === 'select'"
                    v-model="formData[formobj.prop]"
                    :style="formobj.style"
                    size="small"
                    :clearable="true"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                    @change="selectChange($event, index, formobj.prop, formobj)"
                  >
                    <el-option
                      v-for="(options, sIndex) in formobj.options"
                      :key="sIndex"
                      :label="options.label"
                      :value="options.value"
                      :disabled="options.disabled"
                    />
                  </el-select>
                  <!-- select分页查询框 -->
                  <Select
                    v-if="formobj.selectpage || formobj.type === 'selectpage'"
                    v-model="formData[formobj.prop]"
                    class="selectpage"
                    fun-name="downBase"
                    size="small"
                    :radio="formobj.radio"
                    :style="formobj.style"
                    :disabled="formobj.disabled"
                    :rendering-all-keys="formobj.options"
                    :max-num="1"
                    @downBase="
                      selectChange($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- select搜索框 -->
                  <el-select
                    v-if="
                      formobj.searchSelect || formobj.type === 'searchSelect'
                    "
                    v-model="formData[formobj.prop]"
                    size="small"
                    :disabled="formobj.disabled"
                    filterable
                    :clearable="true"
                    remote
                    reserve-keyword
                    :placeholder="formobj.placeholder"
                    :remote-method="
                      (query) => remoteMethod(query, index, formobj.prop)
                    "
                    :loading="searchSelectLoading"
                    @change="selectChange($event, index, formobj.prop)"
                  >
                    <el-option
                      v-for="(item, ssIndex) in formobj.options"
                      :key="ssIndex"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled"
                    />
                  </el-select>
                  <!-- 月选择器 -->
                  <el-date-picker
                    v-if="formobj.dateMonth || formobj.type === 'dateMonth'"
                    v-model="formData[formobj.prop]"
                    type="month"
                    :style="formobj.style"
                    value-format="MM"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                    @input="
                      datePickerSearch($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- 年选择器 -->
                  <el-date-picker
                    v-if="formobj.dateYear || formobj.type === 'dateYear'"
                    v-model="formData[formobj.prop]"
                    type="year"
                    :style="formobj.style"
                    value-format="yyyy"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                    @input="
                      datePickerSearch($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- 年月日时分秒选择器 -->
                  <el-date-picker
                    v-if="formobj.dateTime || formobj.type === 'dateTime'"
                    v-model="formData[formobj.prop]"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    size="small"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                    @input="
                      datePickerSearch($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- 年月日时分秒，开始和结束时间 -->
                  <el-date-picker
                    v-if="
                      formobj.dateTimeRange || formobj.type === 'dateTimeRange'
                    "
                    v-model="formData[formobj.prop]"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                    size="small"
                    type="datetimerange"
                    :disabled="formobj.disabled"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @input="
                      datePickerSearch($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- 时分秒选择器 -->
                  <el-time-picker
                    v-if="formobj.timePicker || formobj.type === 'timePicker'"
                    v-model="formData[formobj.prop]"
                    value-format="HH:mm:ss"
                    format="HH:mm:ss"
                    size="small"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                    :picker-options="formobj.options"
                    @input="
                      datePickerSearch($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- 时分秒选择器，开始和结束时间 -->
                  <el-time-picker
                    v-if="
                      formobj.timePickerIsRange ||
                        formobj.type === 'timePickerIsRange'
                    "
                    v-model="formData[formobj.prop]"
                    value-format="HH:mm:ss"
                    format="HH:mm:ss"
                    is-range
                    size="small"
                    :disabled="formobj.disabled"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                    @input="
                      datePickerSearch($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- 年月日选择器 -->
                  <el-date-picker
                    v-if="formobj.datePicker || formobj.type === 'datePicker'"
                    v-model="formData[formobj.prop]"
                    value-format="yyyy-MM-dd"
                    size="small"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                    @input="
                      datePickerSearch($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- 年月日选择器，开始和介绍年月日 -->
                  <el-date-picker
                    v-if="
                      formobj.datePickerIsRange ||
                        formobj.type === 'datePickerIsRange'
                    "
                    v-model="formData[formobj.prop]"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    size="small"
                    :disabled="formobj.disabled"
                    :placeholder="formobj.placeholder"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @input="
                      datePickerSearch($event, index, formobj.prop, formobj)
                    "
                  />
                  <!-- switch开关 -->
                  <el-switch
                    v-if="formobj.switch || formobj.type === 'switch'"
                    v-model="formData[formobj.prop]"
                    size="small"
                    :disabled="formobj.disabled"
                    @change="formSwitchChange($event, index, formobj.prop)"
                  />
                  <!-- radio单选框 -->
                  <el-radio-group
                    v-if="formobj.radio || formobj.type === 'radio'"
                    v-model="formData[formobj.prop]"
                    :style="formobj.style"
                    :disabled="formobj.disabled"
                    @change="selectChange($event, index, formobj.prop, formobj)"
                  >
                    <el-radio
                      v-for="(options, rIndex) in formobj.options"
                      :key="rIndex"
                      :label="options.value"
                    >
                      {{ options.label }}</el-radio>
                  </el-radio-group>
                  <!-- checkbox复选框 -->
                  <el-checkbox-group
                    v-if="formobj.checkbox || formobj.type === 'checkbox'"
                    v-model="formobj.checkboxvalue"
                    :disabled="formobj.disabled"
                    @change="selectChange($event, index, formobj.prop, formobj,'checkbox')"
                  >
                    <el-checkbox
                      v-for="options in formobj.options"
                      :key="options.value"
                      :label="options.value"
                    >{{ options.label }}
                    </el-checkbox>
                  </el-checkbox-group>

                  <!-- 文件上传 -->
                  <el-upload
                    v-if="formobj.upload || formobj.type === 'upload'"
                    :ref="formobj.prop"
                    :disabled="formobj.disabled"
                    :before-upload="beforeUpload"
                    :accept="formobj.accept ? formobj.accept : ''"
                    :file-list="
                      formobj.uploadObj.fileList
                        ? formobj.uploadObj.fileList
                        : []
                    "
                    action=""
                    :http-request="
                      (file) => {
                        handleFileUpload(file, formobj.prop);
                      }
                    "
                    :limit="formobj.uploadObj.limit"
                    :class="{
                      hide: isUploadButtonHiden(
                        formobj.uploadObj.hideUpload,
                        formobj.uploadObj.limit,
                        formobj.uploadObj.fileList,
                        formobj.disabled,
                      ),
                    }"
                    :on-preview="handlePictureCardPreview"
                    :before-remove="
                      (file, fileList) => {
                        return handleRemove(
                          file,
                          fileList,
                          formobj.uploadObj.limit,
                          formobj.prop,
                          index
                        );
                      }
                    "
                    :on-success="
                      (response, file, fileList) =>
                        uploadSuccess(
                          response,
                          file,
                          fileList,
                          formobj.uploadObj.limit,
                          formobj.prop,
                          index
                        )
                    "
                    :on-remove="
                      (file, fileList) =>
                        uploadRemove(
                          'remove',
                          file,
                          fileList,
                          formobj.uploadObj.limit,
                          formobj.prop,
                          index
                        )
                    "
                    :list-type="
                      formobj.listType ? formobj.listType : 'picture-card'
                    "
                  >
                    <template v-if="formobj.listType === 'filelist'">
                      <div class="filelistbutton">
                        <el-button
                          size="small"
                          type="primary"
                        >点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                          可上传{{ formobj.uploadObj.fileList.length }}/{{
                            formobj.uploadObj.limit
                          }}
                        </div>
                      </div>
                      <div class="el-upload__tip_remake">{{ formobj.uploadObj.title }}</div>

                    </template>
                    <template v-else-if="formobj.listType !== 'filelist'">
                      <i slot="default" class="el-icon-plus">1111</i>
                    </template>
                    <!-- </template> -->
                  </el-upload>

                  <!-- 按钮 -->
                  <el-button
                    v-if="formobj.button || formobj.type === 'button'"
                    size="small"
                    :disabled="formobj.disabled"
                    :loading="formobj.loading"
                    :type="formobj.buttonType || 'primary'"
                    @click="buttonClick(formobj.prop, index)"
                  >
                    {{ formobj.placeholder }}
                  </el-button>
                  <!-- text展示 -->
                  <span
                    v-if="formobj.text || formobj.type === 'text'"
                    v-text="formData[formobj.propname] || formData[formobj.prop]"
                  ></span>
                  <!-- 提示信息 -->
                  <el-tooltip v-show="formobj.tip" placement="top">
                    <div slot="content" v-html="formobj.tip"></div>
                    <i class="el-icon-question" style="display:inline;color:#a1a0a0"></i>
                  </el-tooltip>
                  <!-- 计量单位 -->
                  <span v-if="formobj.unit" class="left10">{{
                    formobj.unit
                  }}</span>
                  <!-- 图标按钮 -->
                  <i
                    v-if="formobj.btnicon"
                    style="padding: 2px; cursor: pointer"
                    :class="formobj.btnicon"
                    class="left10"
                    @click="buttonClick(formobj.prop, index)"
                  ></i>
                  <!-- 文字链接 -->
                  <el-link
                    v-if="formobj.link"
                    :disabled="formobj.linkdisabled"
                    :underline="false"
                    size="small"
                    class="left10"
                    :style="formobj.linkStyle"
                    :type="formobj.buttonType || 'primary'"
                    @click="buttonClick(formobj.prop, index)"
                  >{{ formobj.link }}</el-link>
                  <slot></slot>
                </template>
              </div>
            </el-form-item>
          </div>
        </el-col>
      </e-desc>
    </el-form>
    <el-image-viewer
      v-show="showViewer"
      :on-close="closeViewer"
      :url-list="[dialogImageUrl]"
    />
  </div>
</template>
<!--  zoutiancong封装,date:20210429,详细使用见根目录@/views/home/testForm/testForm.vue,———————————————————————————————————————————————————————————————————————————————— -->
<script>
// import aMap from '../../map/aMap.vue'
// import quillEditor from "@/components/quillEditor/quillEditor.vue";
import Select from "./select";
import eDesc from "./e-desc/e-desc.vue";
// import EDescItem from "../e-desc/e-desc-item.vue";
// import $ from 'jquery';
// 导入组件
export default {
  name: "PublicForm",
  components: {
    // quillEditor,
    Select,
    "el-image-viewer": () =>
      import("element-ui/packages/image/src/image-viewer"),
    eDesc,
    // EDescItem,
  },
  props: {
    inline: {
      type: Boolean,
      required: false,
      default() {
        return true;
      },
    },
    border: {
      type: Boolean,
      required: false,
      default() {
        return true;
      },
    },
    labelPosition: {
      type: String,
      required: false,
      default() {
        return "right";
      },
    },
    type: {
      type: String,
      required: false,
      default() {
        return "edit";
      },
    },
    labelwidth: {
      type: String,
      required: false,
      default() {
        return "";
      },
    },
    formObj: {
      type: Array,
      required: true,
      default() {
        return [];
      },
    },
    formData: {
      type: Object,
      required: true,
    },
    searchSelectOptionsCb: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    const uploadFileUrl =
      this.$store.state.user.uploadFileUrl || process.env.VUE_APP_API;
    return {
      dicarr: {},
      uploaddata: null,
      uploadUrl: uploadFileUrl,
      dialogImageUrl: "",
      showViewer: false, // 显示查看器
      searchSelectLoading: false,
      dialogVisible: false,
      disabled: false,
      searchShow: "", // 高德地图input收索联想
      setSearchVal: [], // 高德地图赋值搜索内容
    };
  },
  computed: {
    istext() {
      const arr = ["录入人", "录入时间"];
      return (label) => {
        if (label) {
          if (arr.indexOf(label) !== -1) {
            return true;
          }
        }
        return false;
      };
    },
    istext1() {
      const arr = ["修改人", "修改时间"];
      return (label) => {
        if (label) {
          if (arr.indexOf(label) !== -1) {
            return true;
          }
        }
        return false;
      };
    },
    // 是否有边框
    borders() {
      return this.border;
    },
    isUploadButtonHiden() {
      return (hideUpload, limit, filelist,dis) => {
        return dis || hideUpload === true ? true : limit === filelist.length;
      };
    },
    computedSpan() {
      return (span) => {
        const a = span || 24;
        // 子组件自己的span，用于父组件计算修改span
        if (a) {
          // props传递的span
          return (24 / 3) * (a / 8);
        } else {
          // 未传递span时，取column
          return 24 / this.column;
        }
      };
    },
  },
  created() {
    if (!this.inline) {
      this.formObj.forEach((t) => {
        const obj = { width: "100%" };
        if (!(t.style && t.style.width)) {
          this.$set(t, "style", obj);
        }
      });
    }
  },
  mounted() {
  },
  methods: {
    colsiShow(formobj, formData) {
      if (typeof formobj.notShow === 'function') {
        return !formobj.notShow(formobj, formData,this)
      } else {
        return !formobj.notShow
      }
    },
    // 日期制空
    datePickerSearch(value, index, prop, formobj) {
      if (value === null) {
        this.formData[prop] = "";
      }
      this.$emit("datePickerSearch", value, index, prop);
    },
    // 表单赋值
    formAssignment(data) {
      // 字段赋值
      function formfz(key,formData,formobj) {
        // 如果是多选的情况
        if (formobj.radio === false) {
          const v1 = data[key].split(',')
          if (v1) {
            const v = []
            for (const a of v1) {
              v.push(formobj.options.filter(t => t.value === a)[0]?.name ?? "")
            }
            formData[key] = v.join()
          } else {
            formData[key] = ''
          }
        } else {
          formData[key] = formobj.options.filter(t => t.value === data[key])[0]?.name ?? "";
        }
      }
      return new Promise((resolve, reject) => {
        Object.keys(this.formData).forEach((key1) => {
          if (data[key1]) {
            if (this.type === "select") {
              if (data[key1 + "name"]) {
                this.formData[key1] = data[key1 + "name"];
              } else {
                // 如果不存在name 去查询自己是否自带options，没有则去查是否有optionsdic
                const a = this.formObj.filter(t => t.prop === key1)
                if (a && a.length > 0) {
                  const a1 = a[0]
                  if (a1.options && a1.options.length > 0) {
                    formfz(key1,this.formData,a1)
                  } else if (a1.optionsdic) {
                    this.$api.utils.sysDictionary({
                      dictCode: a1.optionsdic,
                    }).then(val => {
                      // 遍历如果有相同字典号则不进行ajax
                      this.formObj.forEach((obj1) => {
                        if (obj1.optionsdic === a1.optionsdic) {
                          if (!obj1.options) {
                            // 添加options属性
                            this.$set(obj1, "options", val)
                          } else {
                            obj1.options = val
                          }
                        }
                      });
                      formfz(key1,this.formData,a1)
                    })
                  } else {
                    this.formData[key1] = data[key1] || "";
                  }
                } else {
                  this.formData[key1] = data[key1] || "";
                }
              }
            } else {
              this.formData[key1] = data[key1] || "";
              // 获取是否是checkbox
              const checkboxFromObj = this.formObj.filter(t => t.prop === key1 && t.checkbox)[0]
              if (checkboxFromObj) {
                checkboxFromObj.checkboxvalue = data[key1].split(';')
              }
            }
          }
        })
        Object.keys(this.formObj).forEach((key1) => {
          const _a = this.formObj[key1];
          const listType = _a.listType;
          const key = _a.prop;
          // 附件渲染
          if (listType && listType === "filelist") {
            this.$utils.selectFile(this.formData[key]).then((res) => {
              _a.uploadObj.fileList = res;
            });
          }
        });
        resolve("ok");
      });
    },
    // 渲染表单中的字典
    selectDic() {
      if (this.type !== "select") {
        // 遍历当前配置数组
        const arr = [];
        // Promise.all(promise);
        for (const i in this.formObj) {
          // 定义当前对象值
          const obj = this.formObj[i];
          // 判断是否有字典值
          if (obj.optionsdic) {
            // 判断当前组件是否已经请求过字典值 && this.dicarr[obj.optionsdic].length>0
            if (!this.dicarr[obj.optionsdic]) {
              // push一下 生成添加一下字典属性
              arr.push(obj.optionsdic);
            }
          }
        }
        // 去重
        const newArr = [...new Set(arr)];
        // 生成promise 数组
        const promiseArr = [];
        for (const t of newArr) {
          promiseArr.push(
            this.$api.utils.sysDictionary({
              dictCode: t,
            })
          );
        }
        // 字典赋值
        Promise.all(promiseArr).then((val) => {
          newArr.forEach((t, i) => {
            // 给this添加字典值
            if (!this.dicarr[t]) {
              this.$set(this.dicarr, t, val[i]);
            }
            this.formObj.forEach((obj1) => {
              if (obj1.optionsdic === t) {
                if (!obj1.options) {
                  // 添加options属性
                  this.$set(obj1, "options", val[i]);
                } else {
                  obj1.options = val[i];
                }
              }
            });
          });
        });
      }
    },
    async handleFileUpload(file, prop) {
      const formData = new FormData();
      formData.append("fid", "0"); // 额外参数
      formData.append("fieldid", prop);
      formData.append("be_filename", file.file.name);
      formData.append("file", file.file);
      try {
        const upservefile = await this.$api.utils.upfile(formData);
        this.$message({ message: "上传成功", type: "success" });
        file.onSuccess(upservefile);
      } catch (error) {
        this.$message.warning("文件上传失败");
        file.onError(error);
      }
    },
    // 上传文件前
    beforeUpload(file) {
      const promise = new Promise((resolve) => {
        this.$nextTick(function() {
          resolve(true);
        });
      });
      return promise; // 通过返回一个promis对象解决
    },
    // select变化调用
    selectChange(value, index, prop, formobj) {
      if (formobj && formobj.propname) {
        if (formobj.selectpage) {
          // 多选
          if (formobj.radio === false) {
            this.formData[formobj.propname] = value.map(t => t.label).join(',')
          } else {
            this.formData[formobj.propname] =
            (value.length && value[0].label) || "";
          }
        } else {
          this.formData[formobj.propname] =
            formobj.options.length &&
            formobj.options.filter((t) => t.value === value)[0].label;
        }
      }
      if (formobj.checkbox) {
        this.formData[formobj.prop] = value.join(';')
      }
      this.$emit("selectChange", value, index, prop);
    },
    // input的input事件
    inputINPUT(value, index, prop) {
      this.$emit("inputINPUT", value, index, prop);
    },
    // input的change事件
    inputChange(value, index, prop) {
      this.$emit("inputChange", value, index, prop);
    },
    // 搜索类型select搜索
    remoteMethod(query, index, prop) {
      if (query) {
        this.searchSelectLoading = true;
        this.$emit("querySelectValue", query, index, prop);
        setTimeout(() => {
          this.formObj[index].options = this.searchSelectOptionsCb;
          this.searchSelectLoading = false;
        }, 500);
      } else {
        this.searchSelectOptios = [];
      }
    },
    // switch变化
    formSwitchChange(val, index, prop) {
      this.$emit("formSwitchChange", val, index, prop);
    },
    // 按钮点击事件
    buttonClick(prop, index) {
      this.$emit("buttonClick", prop, index);
    },

    // 文件上传成功回调
    uploadSuccess(response, file, fileList, limit, prop, index) {
      file["id"] = response.attachid;
      this.pushUpload(file, fileList, limit, prop, index);
    },
    // 对文件上传，删除进行赋值，调用form验证
    pushUpload(file, fileList, limit, prop, index, type, id) {
      const $fileList = (this.formObj[index].uploadObj.fileList = fileList);
      // console.log($fileList);
      if ($fileList && $fileList.length > 0) {
        const f = JSON.parse(JSON.stringify($fileList)).map((p) => p.id);
        this.formData[prop] = f.join(",");
      } else {
        // 表示没有数据,把字段置空
        this.formData[prop] = "";
      }
      this.formObj[index].uploadObj.hideUpload = fileList.length === limit; // 文件列表变化后判断当前文件列表长度是否等于限制长度。目的，当长度相等时隐藏文件上传按钮
      this.$refs.ruleForm.validateField(prop); // 调用验证form表单的文件上传
    },
    // 文件删除完成回调
    uploadRemove(response, file, fileList, limit, prop, index) {
      this.pushUpload(file, fileList, limit, prop, index);
    },
    // 文件删除
    handleRemove(file, fileList, limit, prop, index) {
      return new Promise((resolve, reject) => {
        this.$confirm(`确定移除 ${file.name}？`).then(
          async() => {
            try {
              await this.$api.utils.delfile({ id: file.id });
              this.$nextTick(() => {
                this.$message.success("已移除");
              });
              resolve("");
            } catch (error) {
              reject(error);
            }
          },
          (err) => {
            reject(err);
          }
        );
      });
    },
    // 关闭查看器
    closeViewer() {
      this.showViewer = false;
    },
    // 文件预览 || 下载文件
    async handlePictureCardPreview(file) {
      // this.dialogImageUrlClass = 'aaaa'
      if (file.name) {
        const filePath = file.name;
        // 获取最后一个.的位置
        const index = filePath.lastIndexOf(".");
        // 获取后缀
        const ext = filePath.substr(index + 1);
        const flag =
          [
            "png",
            "jpg",
            "jpeg",
            "bmp",
            "gif",
            "webp",
            "psd",
            "svg",
            "tiff",
          ].indexOf(ext.toLowerCase()) !== -1;
        const url = `${process.env.VUE_APP_API1}/attach/upload/${file.name}`;
        if (flag) {
          this.dialogImageUrl = url;
          this.showViewer = true;
        } else {
          this.downloadImage(url);
        }
      }
      // this.clickImage()
      /*  return false
      const name = file.name;
      const downLoad = async() => {
        const responsePromise = await fetch(url);
        const blob = await responsePromise.blob();
        const objectURL = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = objectURL;
        a.download = name;
        a.click();
        a.remove();
      };
      downLoad(); */
    },
    clickImage() {
      this.$nextTick(() => {
        const wrapper = document.getElementsByClassName(
          "el-image-viewer__actions__inner"
        );
        const downImg = document.createElement("i");
        downImg.setAttribute("class", "el-icon-download");
        // for (const i in wrapper) {
        //   wrapper[i].appendChild(downImg)
        //   if (wrapper.length > 0) {
        //     const wrapperElem = wrapper[i]
        //     this.cusClickHandler(wrapperElem)
        //   }
        // }
        wrapper[0].appendChild(downImg);
        if (wrapper.length > 0) {
          this.wrapperElem = wrapper[0];
          this.cusClickHandler();
        }
      });
    },
    cusClickHandler(wrapperElem) {
      this.wrapperElem.addEventListener("click", this.hideCusBtn);
    },
    hideCusBtn(e) {
      const className = e.target.className;
      if (className === "el-icon-download") {
        const imgUrl = document.getElementsByClassName(
          "el-image-viewer__canvas"
        )[0].children[0].src;
        this.downloadImage(imgUrl);
      }
    },
    downloadImage(imgUrl) {
      const tmpArr = imgUrl.split("/");
      const fileName = tmpArr[tmpArr.length - 1];
      window.URL = window.URL || window.webkitURL;
      const xhr = new XMLHttpRequest();
      xhr.open("get", imgUrl, true);
      xhr.responseType = "blob";
      xhr.onload = function() {
        if (this.status === 200) {
          // 得到一个blob对象
          const blob = this.response;
          const fileUrl = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          (document.body || document.documentElement).appendChild(a);
          a.href = fileUrl;
          if ("download" in a) {
            a.download = fileName;
          } else {
            a.setAttribute("download", fileName);
          }
          a.target = "_self";
          a.click();
          a.remove();
        }
      };
      xhr.send();
    },
    // 提交时验证表单，直接在父级调用
    submitForm(callback) {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            callback && callback();
            resolve();
          } else {
            this.$message.warning("请把信息填写完整！");
            reject("reject");
          }
        });
      });
    },
    // 打开表单时清空校验规则
    clearValidate() {
      this.$refs.ruleForm.clearValidate();
    },
    /* 清空表单
				逻辑：
				1 、如果要清空文件上传列表，要传入要清空的upload的字段名，假如多个upload用for循环，调用清空方法！
				2、清空upload之后，还要把upload上传框展示出来，通过字段名比对，获取到在formObj中的下标，通过下标操作对象属性，进行展示
			 */
    resetForm() {
      this.$refs.ruleForm.resetFields();
      // this.$nextTick(() => {
      // 置空propname对应的字段 和 文件列表
      for (const key in this.formObj) {
        if (this.formObj[key].propname) {
          this.formData[this.formObj[key].propname] = undefined;
        }
        if (this.formObj[key].checkboxvalue) {
          this.formObj[key].checkboxvalue = [];
        }
        if (this.formObj[key].upload) {
          // this.$refs[this.formObj[key].prop].clearFiles();
          this.formObj[key].uploadObj.hideUpload = false;
          this.formObj[key].uploadObj.fileList = [];
        }
      }
      // })
    },
    // 单个字段验证
    validateFieldProp(prop) {
      let formValidate = Boolean;
      this.$refs.ruleForm.validateField(prop, (valid) => {
        if (!valid) {
          formValidate = true;
        } else {
          formValidate = false;
        }
      });
      return formValidate;
    },
    // 地图input的input事件
    aMapInput(value, prop) {
      this.$refs[`aMap${prop}`][0].getSearch(value);
    },
    // 子组件返回地图搜索值
    cbSearch(val, prop) {
      this.setSearchVal = val.tips; // 子组件
      this.searchShow = prop; // 显示input输入联想
    },
    // 选中地图值
    selectVal(val, prop, index) {
      // 赋值的时候，拿到键，及formobj的下标，进行赋值
      this.formData[prop] = val.name; // input输入框赋值
      this.formData.district = val.district; // 传入省市区
      const lngLat = {
        lng: val.location.lng,
        lat: val.location.lat,
      };
      this.formData[`${prop}location`] = lngLat;
      this.searchShow = ""; // 隐藏input输入联想
    },
  },
};
</script>
<style lang="scss">
.border{
  .selectform .el-form-item__content{
    width: calc(100% - 120px);
  }
  .el-form-item__error{
    top: 36px !important;
  }
}
.desc-item {
  .el-form-item__content{
    // line-height: 23px;
    width: 100%;
  }
}
// 剔除文件点击删除键取消之后的tip，很恶心
.el-icon-close-tip{
  display: none !important;
}

// .selectform{
//   // margin-bottom: 0 !important;
//   .el-form-item__content{
//     // line-height: 23px;
//   }
// }
</style>
<style lang="scss" scoped>
$width: 190px;
.desc {
  width: 100%;
}
::v-deep .border .desc-row {
  border: none;
}
.desc-item-box {
  display: flex !important;
}
.desc-border {
  border-right: none !important;
}
.text {
  padding: 10px;
  float: left;
}
.text1 {
  padding: 10px;
  float: right;
}
// 表单样式 增加边框样式
.desc-item {
  $borderColor:#ebeef5;
  border-right: 1px solid $borderColor;
  border-bottom: 1px solid $borderColor;
  // border-left: 1px solid #ebeef5;
  // margin: 0px -1px -1px 0px;
  // 修改表单样式
  // 去除elitem外边距
  .el-form-item {
    margin-bottom: 0px !important;
    width: 100%;
  }
  .desc-item-content,
  ::v-deep.el-form-item__content {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    line-height: 1.5;
    width: 100% !important;
    height: 100%;
    .desc-item-label {
      border-right: 1px solid $borderColor;
      background-color: #fafafa;
      display: inline-block;
      padding: 14px 16px;
      flex-grow: 0;
      flex-shrink: 0;
      color: rgba(0, 0, 0, 0.6);
      font-weight: 400;
      font-size: 14px;
      line-height: 1.5;
      height: 100%;
      display: flex;
      align-items: center;
      position: relative;
      .redstar {
        position: absolute;
        top: 17px;
        left: 9px;
        font-size: 18px;
        color: red;
      }
    }
    .desc-item-value {
      display: flex;
      background: #fff;
      padding: 10px 5px 21px 5px;
      flex-grow: 1;
      overflow: hidden;
      word-break: break-all;
      height: 100%;
      display: flex;
      align-items: center;
      color: #444;
      // span {
      // color: #aaa;
      // }
      // 空数据时展示的内容
      &:empty::after {
        content: "--";
      }
      button {
        span {
          color: #fff;
        }
      }
      // 文件上传按钮
      .filelistbutton {
        display: flex;
        button {
          margin-right: 20px;
        }
      }
    }
    .tips{
      position: absolute;
    bottom: -5px;
    /* color: #b5b5b5; */
    font-size: 11px;
    }
    &.small {
      .desc-item-label,
      .desc-item-value {
        padding: 10px 14px;
      }
    }
  }
}

.demo-ruleForm {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  // justify-content:space-around;
}

form {
  overflow: hidden;
}
.selectpage {
  width: $width;
}
::v-deep.el-input {
  width: $width;
}
// 错误提示
::v-deep .el-form-item__error{
  color: #F56C6C;
  font-size: 12px;
  line-height: 1;
  top: 46px;
  position: absolute;
  left: 3px;
  // z-index: 100;
}
::v-deep.el-select {
  width: $width;
}

::v-deep.el-date-editor.el-input {
  width: $width;
}
::v-deep.el-date-editor .el-range-separator {
  width: 20px !important;
}
::v-deep.el-range-editor--small.el-input__inner {
  width: 400px;
}

.hide {
  ::v-deep .el-upload--filelist,
  ::v-deep .el-upload__tip {
    display: none;
  }
}

.amap_div {
  overflow: hidden;
  height: 400px;
  width: 600px;
  position: relative;

  .sreach_ul {
    position: absolute;
    top: 1;
    background-color: white;
    z-index: 9;
    min-width: 210px;
    float: auto;
    height: 200px;
    overflow: auto;
    padding: 0 20px;
    line-height: 24px;
  }
}
.title {
  width: 100%;
  font-size: 18px;
  color: black;
  padding: 10px;
  border-bottom: none;
  margin-bottom: 0px;
  position: relative;
  background-color: #f2f2f2;
  height: 40px;
  padding-left: 30px;
  &::before {
    position: absolute;
    top: 0;
    height: 20px;
    width: 4px;
    margin-right: 5px;
    /* margin-top: 10px; */
    background-color: #409eff;
    position: absolute;
    top: 50%;
    left: 10px;
    transform: translateY(-50%);
  }
}
</style>
